//
//  HMNetworkingTools.swift
//  Swift中的单利
//
//  Created by Apple on 16/11/14.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import AFNetworking

enum HTTPMethod : Int {
    case GET = 0
    case POST
    
}

class HMNetworkingTools: AFHTTPSessionManager {
    
    //创建单利
    static let shared: HMNetworkingTools = {
        
        let tool = HMNetworkingTools()
        tool.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json","text/json","text/javascript","text/html") as? Set<String>
        
        //设置默认响应
        tool.responseSerializer = AFHTTPResponseSerializer()
        tool.requestSerializer = AFJSONRequestSerializer()
        

        
        return tool;
    }()
    
    
    //加载网络请求,闭包的参数不需要写
    
    func request(method:HTTPMethod,URLString: String, parameters: Any?,finish:@escaping (Any?,Error? )->()) {
        
       
        let successClosure = { (task:URLSessionDataTask, responseObject:Any?) in
            
            finish(responseObject,nil)
            
        }
        
        let filureClosure = { (tesk:URLSessionDataTask?, error:Error) in
            
            finish(nil, error)
            
            print(error)
            
    }
        
        
        if method == .GET {
        
            self.get(URLString, parameters: parameters, progress: nil, success: successClosure, failure: filureClosure)
            
        }else{
            
              self.post(URLString, parameters: parameters, progress: nil, success: successClosure, failure: filureClosure)
        }
        
    }
    
    
    

}



